package com.software.software.controler;

import com.software.software.model.*;
import com.software.software.mapper.UserMapper;
import com.software.software.model.server.EmailUtil;
import com.software.software.model.server.getMd5;
import com.software.software.model.server.searchMap;
import com.software.software.server.UploadUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class serveController {
    @Resource
    private UserMapper userMapper;
    private searchMap map= new searchMap();
    private com.software.software.model.server.getMd5 getMd5 = new getMd5();
    Date dNow = new Date( );
    SimpleDateFormat ft = new SimpleDateFormat("yyyyMMddHHmmss");
//    提供登录服务
    @PostMapping("/login")
    public String login(@RequestParam("loginName") String loginName, @RequestParam("loginPwd") String loginPwd, HttpSession session,
                        Model model,HttpServletResponse response) {
        userInfo userInfo;
        String rightPwd = userMapper.searchPwd(loginName);

        if (rightPwd == null) {
            model.addAttribute("msg","账号无效");
            return "login";
        }
        userInfo = userMapper.searchUserInfo(map.get_map(null,null,loginName,null));
//        比对账号密码是否正确
        if (userInfo != null && rightPwd.equals(getMd5.getMD5String(loginPwd))) {
//            更新登录时间
            userMapper.upDateUserInfo(map.makeMap("lastLoginTime",ft.format(dNow),"userId",String.valueOf(userInfo.userId)));
//            返回账号信息
            session.setAttribute("userInfo",userInfo);
            Cookie cookie2 = new Cookie("userId",String.valueOf(userInfo.userId));
            response.addCookie(cookie2);
            if (userInfo.userLevel > 0) return "redirect:/admin";
//            人脸识别
            if(userInfo.haveFace==1)
                return "redirect:/faceCheck";
                return "redirect:/main";
        } else {
            model.addAttribute("msg","账号密码错误");
            return "login";
        }
    }
    @ResponseBody
    @PostMapping("/logout")
    public String logout(@CookieValue("userId") Cookie cookie2,
                         HttpServletResponse rep, HttpServletRequest req) {
//        清空账号信息
        req.getSession().invalidate();
        cookie2.setMaxAge(0);
        rep.addCookie(cookie2);
        return "success";
    }
//提供注册服务
    @ResponseBody
    @PostMapping("/signUp")
    public String signUp(@RequestParam Map<String,String> param, HttpSession session, Model model, HttpServletResponse response) {
        int state=0;
//        查找账号/邮箱相同用户数
        state = userMapper.countCommonUser(param);
        if (session.getAttribute("userCheckCode") == null) {
            return "验证码失效或未发送";
        } else if (!((checkCodeInfo)session.getAttribute("userCheckCode")).userEmail.equals(param.get("userEmail"))) {
            return "验证邮箱不符";
        } else if (!((checkCodeInfo)session.getAttribute("userCheckCode")).is_right(param.get("userCheckcode"))) {
            return "验证码错误";
        }
        if (state != 0) {
            int commonName = userMapper.countCommonUser(map.get_map(null,null,param.get("loginName"),null));
            if (commonName != 0) return "用户名重复";
            else return "邮箱已经被注册";
        } else {
            state=userMapper.save(param);
            userInfo userInfo=userMapper.searchUserInfo(map.get_map(null,null,param.get("loginName"),null));

            if (state == 1) {
                userMapper.upDateUserInfo(map.makeMap("lastLoginTime",ft.format(dNow),"userId",String.valueOf(userInfo.userId)));
                session.setAttribute("userInfo",userInfo);
                Cookie cookie2 = new Cookie("userId",String.valueOf(userInfo.userId));
                response.addCookie(cookie2);
                System.out.println("注册成功");
                return "注册成功";
            } else {
                return "注册失败";
            }
        }
    }
//  提交blog的评论
    @ResponseBody
    @PostMapping("/comment/submit")
    public String submitComment(@RequestParam Map<String,String> param, HttpSession session, Model model, HttpServletResponse response) {
        int state=0;
        commentInfo commentInfo = new commentInfo();
        commentInfo.blogId = Integer.valueOf(param.get("blogId"));
        commentInfo.userId = ((userInfo)session.getAttribute("userInfo")).userId;
        commentInfo.content = param.get("content");
        commentInfo.createDate = param.get("createDate");
        state=userMapper.saveComment(commentInfo);

        return state == 1 ? "success" : "reject";
    }
    @ResponseBody
    @PostMapping("/submit/blog")
    public String submitBlog(@RequestParam Map<String,String> param, HttpSession session, Model model, HttpServletResponse response) {
        int state=0;
        System.out.println(param);
        param.put("userId",String.valueOf(((userInfo)session.getAttribute("userInfo")).userId));
        //获得文章标签数组
        String tags = param.get("tags");
        String[] blogTags = tags.split(",");
//            文章标签列表
        List<String> blogTagsList = new ArrayList<String>();
//            所有标签列表
        List<String> totalTags = userMapper.allTagsName();
        int currentId = totalTags.size() + 1;
        for (int i = 0; i < blogTags.length; i ++ ) {
//                获取文章标签列表
            blogTagsList.add(blogTags[i]);
            if (!totalTags.contains(blogTags[i])) {
//                    插入新标签信息
                userMapper.saveTagInfo(map.makeMap("tagId",String.valueOf(currentId),"content",blogTags[i]));
//                    插入标签栏
                userMapper.saveBlogTag(currentId);
//                    更新所有标签列表
                totalTags.add(blogTags[i]);
                currentId ++;
            }
        }
//            获取文章对应的标签向量 0 1表示是否有该标签
        String blogTagInfo = String.valueOf(userMapper.countBlogs("")+1) + ",";
        for (int i = 0; i < totalTags.size(); i ++ ) {
            if (blogTagsList.contains(totalTags.get(i))) {
                blogTagInfo = blogTagInfo.concat(String.valueOf(1));
            } else {
                blogTagInfo = blogTagInfo.concat(String.valueOf(0));
            }
            if (i+1!=totalTags.size()) blogTagInfo = blogTagInfo.concat(",");
        }
        System.out.println(blogTagInfo);
        state=userMapper.saveBlog(param);
        state=userMapper.saveTags(blogTagInfo);
        return state == 1 ? "success" : "reject";
    }
    @ResponseBody
    @PostMapping("/upDate/blog")
    public String upDataBlog(@RequestParam Map<String,String> param, HttpSession session, Model model, HttpServletResponse response) {
        int state=0;
        System.out.println(param);
        param.put("userId",String.valueOf(((userInfo)session.getAttribute("userInfo")).userId));
        state=userMapper.upDateBlog(param);
        if (state == 1) {
            //获得文章标签数组
            String tags = param.get("tags");
            String[] blogTags = tags.split(",");
//            文章标签列表
            List<String> blogTagsList = new ArrayList<String>();
//            所有标签列表
            List<String> totalTags = userMapper.allTagsName();
            int currentId = totalTags.size() + 1;
            for (int i = 0; i < blogTags.length; i ++ ) {
//                获取文章标签列表
                blogTagsList.add(blogTags[i]);
                if (!totalTags.contains(blogTags[i])) {
//                    插入新标签信息
//                    System.out.println("saveTagInfo tagId:"+String.valueOf(currentId)+" content:"+blogTags[i]);
                    userMapper.saveTagInfo(map.makeMap("tagId",String.valueOf(currentId),"content",blogTags[i]));
//                    插入标签栏
//                    System.out.println("saveBlogTag tagId:"+String.valueOf(currentId));
                    userMapper.saveBlogTag(currentId);
//                    更新所有标签列表
                    totalTags.add(blogTags[i]);
                    currentId ++;
                }
            }
//            获取文章对应的标签向量 0 1表示是否有该标签
            String blogTagInfo = "";
            for (int i = 0; i < totalTags.size(); i ++ ) {
                blogTagInfo = blogTagInfo.concat("`" + String.valueOf(i+1) + "`=");
                if (blogTagsList.contains(totalTags.get(i))) {
                    blogTagInfo = blogTagInfo.concat(String.valueOf(1));
                } else {
                    blogTagInfo = blogTagInfo.concat(String.valueOf(0));
                }
                if (i+1!=totalTags.size()) blogTagInfo = blogTagInfo.concat(",");
            }
            blogTagInfo = blogTagInfo.concat(" where blogId = " + String.valueOf(param.get("blogId")));
//                        System.out.println(blogTagInfo);
            state=userMapper.updateTags(blogTagInfo);
        }
        return state == 1 ? "success" : "reject";
    }
    @ResponseBody
    @PostMapping("/upDate/userInfo")
    public String updateUserInfo(@RequestParam Map<String,String> param,HttpSession session,HttpServletResponse rep) {
        int state = 0;
        System.out.println(param);
        if (((userInfo)session.getAttribute("userInfo")).userId != Integer.valueOf(param.get("userId"))) return "reject";
        //管理员 修改用户权限
        if (param.get("userLevel") != null) {
            if (((userInfo)session.getAttribute("userInfo")).userLevel != 2) return "reject";
        }
        state = userMapper.upDateUserInfo(param);
//        用户更新信息 返回新用户信息   管理员更新权限不需更新用户信息，会覆盖管理员登录信息
        if (param.get("userLevel") == null && state == 1) {
            Map<String,String> m = new HashMap<String,String>();
            m.put("userId",String.valueOf(param.get("userId")));
            userInfo updataUserInfo = userMapper.searchUserInfo(m);
            session.setAttribute("userInfo",updataUserInfo);
        }
        return state == 1 ? "success" : "reject";
    }
    @ResponseBody
    @PostMapping("/upDate/userPwd")
    public String updateUserPwd(@RequestParam Map<String,String> param,HttpSession session,HttpServletResponse rep) {
        int state = 0;
        System.out.println(param);
        userInfo userInfo = (userInfo)session.getAttribute("userInfo");
        //邮箱找回密码时通过邮箱索引
        if (userInfo == null) {
            userInfo = userMapper.searchUserInfo(param);
            if(userInfo == null) {
                return "邮箱未注册";
            }
        }
        String oldPwd = userMapper.searchPwd(userInfo.loginName);
        if (param.get("oldPwd") != null && param.get("oldPwd") != "") {
            if (oldPwd.equals(getMd5.getMD5String((param.get("oldPwd"))))) {
                param.put("userId",String.valueOf(userInfo.userId));
                state = userMapper.upDateUserPwd(param);
            } else {
                return "原密码错误！";
            }
        } else {
            if (session.getAttribute("userCheckCode")!=null && ((checkCodeInfo)session.getAttribute("userCheckCode")).is_right(param.get("inputCode"))) {
                param.put("userId",String.valueOf(userInfo.userId));
                state = userMapper.upDateUserPwd(param);
            } else {
                return "验证码错误！";
            }
        }
        if (state == 1) {
            session.removeAttribute("userInfo");
        }
        return state == 1 ? "success" : "验证码失效";
    }
//查询blog
    @ResponseBody
    @PostMapping("/search")
    public List<blogInfo> search(@RequestParam Map<String,String> param){
        List<blogInfo>  list= new ArrayList<blogInfo>();
        List<Integer> listS = null;
//        标签Id查询博客
        if (param.get("tagId") != null && param.get("tagId") != "") {
            listS=userMapper.searchByTagId(Integer.valueOf(param.get("tagId")));
            for (int i = 0; i < listS.size(); i ++ ) {
                System.out.println(listS.get(i));
                blogInfo b = userMapper.searchBlog(String.valueOf(listS.get(i)));
//                博客被删除 跳过循环
                if (b == null) {
                    continue;
                }
                list.add(b);
            }
        } else list=userMapper.search(param);
//所有标签名
        List<String> alltags = userMapper.allTagsName();
        for (int i = 0; i < list.size(); i ++ ) {
//            发布者信息
            list.get(i).userInfo = userMapper.searchUserInfo(map.get_map(String.valueOf(list.get(i).userId),null,null,null));
//            评论数
            list.get(i).commentNum = userMapper.searchComments(list.get(i).blogId).size();
//            标签Id列表
            List<Integer> blogTagId = new ArrayList<Integer>();
//            标签名列表
            List<String> blogtags = new ArrayList<String>();
//            获得该文章对应的标签向量
            Map<String,Integer> m = userMapper.getBlogTagId(list.get(i).blogId);

            for (String key : m.keySet()) {
                if (key.equals("blogId")) continue;
                if (m.get(key) != null && m.get(key) == 1) {
                    blogtags.add(alltags.get(Integer.valueOf(key) - 1));
                    blogTagId.add(Integer.valueOf(key));
                }
            }
            list.get(i).blogTagId = blogTagId;
            list.get(i).blogTags = blogtags;
        }
        return list;
    }
    @ResponseBody
    @PostMapping("/search/tags")
    public List<String> searchTags() {
        return userMapper.allTagsName();
    }
    @ResponseBody
    @PostMapping("/search/files")
    public List<fileInfo> searchFiles() {
        List<fileInfo>  list= new ArrayList<fileInfo>();
        list = userMapper.searchFiles();
        for (int i = 0; i < list.size(); i ++ ) {
            list.get(i).userInfo = userMapper.searchUserInfo(map.get_map(String.valueOf(list.get(i).userId),null,null,null));
        }
        return list;
    }
    @ResponseBody
    @PostMapping("/search/serverInfo")
    public Map<String,String> searchSeverInfo(){
        Map<String,String> m = map.makeMap("blogNum",String.valueOf(userMapper.search(map.makeMap("userId","-1","blogId","-1")).size()),
                "CommentNum",String.valueOf(userMapper.countComments("")),
                "userNum",String.valueOf(userMapper.countCommonUser(map.makeMap("userLevel","0"))),
                "manageUserNum",String.valueOf(userMapper.countCommonUser(map.makeMap("userLevel","1"))));
        return m;
    }
    @ResponseBody
    @PostMapping("/search/userInfo")
    public List<userInfo> searchUserInfo(@RequestParam Map<String,String> param) {
        int state = 0;
        List<userInfo> list = null;
        list = userMapper.searchUser(param);
        for (int i = 0; i < list.size(); i ++ ) {
            list.get(i).blogNum = userMapper.search(map.get_map(String.valueOf(list.get(i).userId),null,null,null)).size();
        }
        return list;
    }
//查询blog的评论
    @ResponseBody
    @PostMapping("/search/comment")
    public List<commentInfo> searchCommentList(@RequestParam("blogId") int blogId) {
        List<commentInfo>  list=null;
        list=userMapper.searchComments(blogId);
        for (int i = 0; i < list.size(); i ++ ) {
            list.get(i).userInfo = userMapper.searchUserInfo(map.get_map(String.valueOf(list.get(i).userId),null,null,null));
        }
        return list;
    }
    @ResponseBody
    @PostMapping("/blog/{blogId}")
    public blogInfo searchBlog(@PathVariable("blogId") int blogId) {
        blogInfo blog= userMapper.searchBlog(String.valueOf(blogId));
        blog.userInfo = userMapper.searchUserInfo(map.get_map(String.valueOf(blog.userId),null,null,null));

        List<String> alltags = userMapper.allTagsName();
        List<Integer> blogTagId = new ArrayList<Integer>();
        List<String> blogtags = new ArrayList<String>();
        Map<String,Integer> m = userMapper.getBlogTagId(blog.blogId);
        for (String key : m.keySet()) {
            if (key.equals("blogId")) continue;
            if (m.get(key) != null && m.get(key) == 1) {
                blogtags.add(alltags.get(Integer.valueOf(key)-1));
                blogTagId.add(Integer.valueOf(key));
            }
        }
        blog.blogTagId = blogTagId;
        blog.blogTags = blogtags;
        return blog;
    }
    @ResponseBody
    @PostMapping("/delete/blog")
    public int deleteBlog(@RequestParam Map<String,String> param,HttpSession session) {
        int state = 0;
        for (String value : param.values()) {
            blogInfo blogInfo = userMapper.searchBlog(value);
//            博客不存在
            if (blogInfo == null) return 0;
            userInfo targetUserInfo = userMapper.searchUserInfo(map.get_map(String.valueOf(blogInfo.userId),null,null,null));
//            不是管理员删除 或不是本人删除
            if (targetUserInfo == null ||
                    (((userInfo)session.getAttribute("userInfo")).userLevel <= targetUserInfo.userLevel &&
                    ((userInfo)session.getAttribute("userInfo")).userId != targetUserInfo.userId)
            ) return 0;
        }
        for (String value : param.values()) {
            state = userMapper.deleteBlog(value);
        }

        return state;
    }
    @ResponseBody
    @PostMapping("/delete/file")
    public int deleteFile(@RequestParam Map<String,String> param,HttpSession session) {
        int state = 0;
        for (String value : param.values()) {
            state = userMapper.deleteFile(value);
        }
        return state;
    }
    @ResponseBody
    @PostMapping("/delete/user")
    public String deleteUser(@RequestParam Map<String,String> param,HttpSession session) {
        int state = 0;
        for (String value : param.values()) {
            userInfo targetUserInfo = userMapper.searchUserInfo(map.get_map(value,null,null,null));
            if (targetUserInfo == null ||
                    (((userInfo)session.getAttribute("userInfo")).userLevel <= targetUserInfo.userLevel &&
                    ((userInfo)session.getAttribute("userInfo")).userId != targetUserInfo.userId)
            ) return "reject";
        }
        for (String value : param.values()) {
            userMapper.deleteUser(value);
        }
        return "success";
    }
    @ResponseBody
    @PostMapping("/delete/comment")
    public String deleteComment(@RequestParam Map<String,String> param,HttpSession session) {
        int state = 0;
        for (String value : param.values()) {
            commentInfo commentInfo = userMapper.searchComment(value);
            if (commentInfo == null) return "reject";
            userInfo targetUserInfo = userMapper.searchUserInfo(map.get_map(String.valueOf(commentInfo.userId),null,null,null));
            if (targetUserInfo == null ||
                    (((userInfo)session.getAttribute("userInfo")).userLevel <= targetUserInfo.userLevel &&
                    ((userInfo)session.getAttribute("userInfo")).userId != targetUserInfo.userId)
            ) return "reject";
        }
        for (String value : param.values()) {
            userMapper.deleteComment(value);
        }
        return "success";
    }
    @ResponseBody
    @PostMapping("/upload")
    public String[] fileUpload(HttpSession session,@RequestPart MultipartFile img,Model model,HttpServletResponse rep,HttpServletRequest request) throws IOException {
        System.out.println("上传的信息"+img.getSize());
        String[] list = new String[2];
        if (!img.isEmpty()) {
//            获得文件名
            String OriginalFilename = img.getOriginalFilename();
            Map<String,String> m = new HashMap<String, String>();
            m.put("userId",String.valueOf(((userInfo)session.getAttribute("userInfo")).userId));
            m.put("fileName",OriginalFilename);
            fileInfo file = userMapper.searchCommonFile(m);
//            映射新文件名 保存后缀
            String fileName = String.valueOf(userMapper.countFiles("")+1) + OriginalFilename.substring(OriginalFilename.lastIndexOf('.'));
//              有相同文件 不上传
            if (file != null) {
                list[0] = file.fileUrl;
                list[1] = request.getContextPath()+UploadUtils.workLowPath()+file.fileUrl.substring(file.fileUrl.lastIndexOf('/'));
                System.out.println("url"+list[0]);
                System.out.println("workUrl:"+list[1]);
                Cookie cookie = new Cookie("imgUrl",list[0]);
                rep.addCookie(cookie);
                return list;
            }
//            获得本地路径
            File fileDir = UploadUtils.getImgDirFile();
//            根据文件名创建新文件
            File newFile = new File(fileDir.getAbsoluteFile()+File.separator+fileName);
//            接收数据传送到新文件
            img.transferTo(newFile);
            String projectServerPath = request.getScheme() + "://"+request.getServerName()+":" +
                    request.getServerPort() + request.getContextPath();
//            绝对路径
            list[0] = projectServerPath+UploadUtils.workLowPath()+fileName;
//            相对路径
            list[1] = request.getContextPath()+UploadUtils.workLowPath()+fileName;
            fileInfo fileInfo = new fileInfo();
            fileInfo.fileName = OriginalFilename;
            fileInfo.fileUrl = list[0];
            fileInfo.userId = ((userInfo)session.getAttribute("userInfo")).userId;
            userMapper.savefile(fileInfo);
            Cookie cookie = new Cookie("imgUrl",list[0]);
            rep.addCookie(cookie);
            return list;
        } else {
            list[0] = "reject";
            return list;
        }
    }


    private Date date = new Date();
    @Resource
    private EmailUtil emailUtil;
    @ResponseBody
    @PostMapping("/email")
    public String email(@RequestParam Map<String,String> param,HttpSession session){
        if (param.get("checkUser") != null && param.get("checkUser").equals("true")) {
            if (!((userInfo)session.getAttribute("userInfo")).userEmail.equals(param.get("userEmail"))) {
                return "rejust";
            }
        }
        checkCodeInfo checkInfo = new checkCodeInfo();
        checkInfo.userEmail = param.get("userEmail");
        checkInfo.createTime = date.getTime();
        userInfo userInfo = userMapper.searchUserInfo(map.get_map(null,null,null,param.get("userEmail")));
        checkInfo.checkCode = emailUtil.sendMail(param.get("userEmail"),userInfo);
        System.out.println(checkInfo.checkCode);
        session.setAttribute("userCheckCode",checkInfo);
        return "access";
    }

//    @PostMapping("")
}
